
// ===============================================================================================================
// -*- C++ -*-
//
// ReferenceCountable.hpp - An interface class for all reference countable objects.
//
// Copyright (c) 2011 Guilherme R. Lampert
// guilherme.ronaldo.lampert@gmail.com
//
// This code is licenced under the MIT license.
//
// This software is provided "as is" without express or implied
// warranties. You may freely copy and compile this source into
// applications you distribute provided that the copyright text
// above is included in the resulting source code.
//
// ===============================================================================================================

#ifndef __REFERENCE_COUNTABLE_HPP__
#define __REFERENCE_COUNTABLE_HPP__

///
/// ReferenceCountable -- Provides reference counting through the methods AddRef() and Release().
/// When you create an object, calling a method which starts with 'Create', a new object is created, and you get a pointer to it.
/// If you no longer need the object, you have to call Release(). This will destroy the object, if AddRef() was not called
/// in another part of you program, signaling that the object is still in use.
///
class ReferenceCountable {

public:

	// Starts with one.
	ReferenceCountable(void) : refCount(1) { /**/ }

	/// Increment the reference count by one, indicating that this object has another pointer which is referencing it.
	/// \return The current reference count (number of pointers referencing this object).
	virtual unsigned long AddRef(void) const = 0;

	/// Decrement the reference count by one, indicating that a pointer to this object is no longer referencing it.
	/// If the reference count goes to zero, it is assumed that this object is no longer in use and it is automatically deleted.
	/// \return The current reference count (number of pointers referencing this object). If the return is equal to zero, the object was deleted.
	virtual unsigned long Release(void) const = 0;

	/// Return the number pointers currently referencing this object.
	virtual unsigned long ReferenceCount(void) const = 0;

protected:

	virtual ~ReferenceCountable(void) { /* Not allowed to be directly deleted */ }

	mutable volatile unsigned long refCount; ///< The reference counter.
};

#endif // __REFERENCE_COUNTABLE_HPP__